﻿// ////////////////////////////////////////////////////////////////////////////
// 
// SWE Case Tool
// 
// Solution:	CaseTool
// Project:		1. CaseTool
// Filename:	ProjectFactory.cs
// 
// File Created:	21:07 30.05.2013 
// Last Changed:	18:11 05.06.2013
// 
// ////////////////////////////////////////////////////////////////////////////

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using SWE.CaseTool.GUI;

namespace SWE.CaseTool
{
	/// <summary>
	/// Creates loads and saves a project. This class primarely containts the import/export
	/// functionallity.
	/// For easier implentation we used a BinaryFormatter to save the Project data. The binary formatter
	/// isn't
	/// flexible, but very easy to use.
	/// Becauase the new project requirements dropped the xml part, we decided to switch to binary
	/// formatter,
	/// which leads to nearly zero minutes implementation time.
	/// </summary>
	public static class ProjectFactory
	{
		/// <summary>
		/// Creates a new project.
		/// </summary>
		/// <returns></returns>
		public static Project CreateProject() { return new Project(); }

		/// <summary>
		/// Loads the project from the given file.
		/// </summary>
		/// <param name="path">The file which contains the project</param>
		/// <returns>
		/// The loaded project
		/// </returns>
		/// <exception cref="System.ArgumentException">The file does not exist</exception>
		/// <exception cref="System.ArgumentNullException">The loaded file had the wrong type</exception>
		public static Project LoadProject(string path)
		{
			if (!File.Exists(path))
			{
				throw new ArgumentException("The file does not exist: " + path);
			}

			Project project;
			using (var stream = new FileStream(path, FileMode.Open))
			{
				var formatter = new BinaryFormatter();

				project = formatter.Deserialize(stream) as Project;
				if (project == null)
				{
					throw new ArgumentNullException("The loaded file had the wrong type");
				}
			}

			return project;
		}

		/// <summary>
		/// Saves the project.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <param name="project">The project.</param>
		public static void SaveProject(string path, Project project)
		{
			using (var stream = new FileStream(path, FileMode.Create))
			{
				var formatter = new BinaryFormatter();
				formatter.Serialize(stream, project);
				stream.Close();
			}
		}
	}
}